<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>4-超时与取消请求</title>
</head>

<body>
    <button>发送请求</button>
    <button>取消请求</button>

    <script>
        const buttons = document.querySelectorAll('button')

        let xhr
        buttons[0].onclick = () => {
            xhr = new XMLHttpRequest()
            xhr.open('GET', 'http://localhost:8081/delay-server')
            // xhr.timeout = 2000
            // xhr.ontimeout = () => {
            //     alert('超时错误！')
            // }
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status <= 299) {
                        console.log('----', xhr.status, xhr.responseText)
                    }
                }
            }
            xhr.send()
        }
        buttons[1].onclick = () => {
            xhr.abort()
            console.log('中断请求')
        }

    </script>
</body>

</html>